<template>
    <div>
        <!-- 反馈列表 -->
        <el-table :data="feedbacks" style="width: 100%">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="content" label="内容" />
            <el-table-column label="图片">
                <template #default="scope">
                    <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" alt="Feedback Image" style="max-width: 100px;" />
                    <span v-else>加载中...</span>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="200" :formatter="formatDate" />
            <el-table-column prop="updatedAt" label="更新时间" width="200" :formatter="formatDate" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" @click="deleteFeedback(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑反馈对话框 -->
        <el-dialog title="编辑反馈" v-model="editDialogVisible" width="50%">
            <el-form :model="selectedFeedback" label-width="120px">
                <el-form-item label="类型">
                    <el-input v-model="selectedFeedback.type"></el-input>
                </el-form-item>
                <el-form-item label="内容">
                    <el-input v-model="selectedFeedback.content"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <!-- 图片上传组件 -->
                    <el-upload
                        :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :show-file-list="false"
                    >
                        <el-button type="primary">上传图片</el-button>
                    </el-upload>
                    <!-- 显示当前图片 -->
                    <img v-if="selectedFeedback.imageUrl" :src="selectedFeedback.imageUrl" alt="Feedback Image" style="max-width: 300px; margin-top: 10px;" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateFeedback">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import service from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';

// 反馈数据
const feedbacks = ref([]);

// 编辑对话框显示状态
const editDialogVisible = ref(false);

// 当前选中的反馈
const selectedFeedback = ref({});

/**
 * 格式化日期函数
 */
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const date = new Date(cellValue);
    if (isNaN(date.getTime())) {
        console.error(`Invalid date value: ${cellValue}`);
        return 'Invalid Date';
    }
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    };
    return new Intl.DateTimeFormat('zh-CN', options).format(date).replace(/\//g, '-');
};

/**
 * 获取反馈数据
 */
const fetchFeedbacks = async () => {
    try {
        const response = await service.get('/feedback'); // 确保这是正确的API端点
        feedbacks.value = response.data.data.map(item => ({ ...item, imageUrl: null }));

        // 自动加载每条反馈的图片
        for (const feedback of feedbacks.value) {
            if (feedback.photoUrl) {
                loadImage(feedback.photoUrl, feedback);
            }
        }
    } catch (error) {
        console.error('获取反馈数据失败', error);
    }
};

/**
 * 加载图片
 */
const loadImage = (imagePath, feedback) => {
    console.log('加载图片:', imagePath);

    service.get(`/images/${imagePath}`, {
        responseType: 'blob'
    })
        .then(response => {
            feedback.imageUrl = URL.createObjectURL(response.data);
            console.log('加载图片 URL:', feedback.imageUrl);
        })
        .catch(error => {
            console.error('图片加载失败', error);
            ElMessage.error('图片加载失败，请重试');
        });
};

/**
 * 显示编辑对话框
 */
const showEditDialog = (feedback) => {
    selectedFeedback.value = { ...feedback };
    editDialogVisible.value = true;
};

/**
 * 更新反馈信息
 */
const updateFeedback = async () => {
    try {
        await service.put(`/feedback/${selectedFeedback.value.id}`, selectedFeedback.value);
        await fetchFeedbacks();
        editDialogVisible.value = false;
        ElMessage.success('反馈信息更新成功');
    } catch (error) {
        console.error('更新反馈信息失败', error);
        ElMessage.error('反馈信息更新失败');
    }
};

/**
 * 删除反馈
 */
const deleteFeedback = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该反馈吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await service.delete(`/feedback/${id}`);
        await fetchFeedbacks();
        ElMessage.success('反馈删除成功');
    } catch (error) {
        console.error('删除反馈失败', error);
        ElMessage.error('反馈删除失败');
    }
};

/**
 * 图片上传前的处理
 * @param {File} file - 上传的文件
 * @returns {boolean} 是否阻止默认上传行为
 */
const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);

    service.post('/upload/image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
        .then(response => {
            handleUploadSuccess(response.data);
            console.log('图片上传成功，路径为:', response.data);
        })
        .catch(error => {
            handleUploadError(error);
        });

    return false; // 阻止默认上传行为
};

/**
 * 图片上传成功
 * @param {string} response - 图片路径
 */
const handleUploadSuccess = (response) => {
    if (response) {
        selectedFeedback.value.photoUrl = response;
        loadImage(response, selectedFeedback.value);
        // 直接使用上传成功后的图片路径
        selectedFeedback.value.imageUrl = response;
        console.log('图片上传成功，路径为:', selectedFeedback.value.photoUrl);
    }
};

/**
 * 图片上传失败
 * @param {Error} error - 错误信息
 */
const handleUploadError = (error) => {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

// 组件挂载时获取反馈数据
onMounted(() => {
    fetchFeedbacks();
});
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>